/**
 * 
 */
package com.terrence.sso.token.client.web.filter;

import java.io.IOException;
import java.util.HashMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.terrence.sso.token.client.web.Config;
import com.terrence.sso.token.client.web.Constant;
import com.terrence.sso.token.client.web.server.SSOTokenVerifyProxy;
import com.terrence.sso.token.common.utils.StringUtils;
import com.terrence.sso.token.common.utils.URLUtils;

/**
 * @author wuchuang
 *
 * 2017年3月8日 上午9:28:06
 */
public class SSOClientFilter implements Filter {

	public void init(FilterConfig filterConfig) throws ServletException {

	}

	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) servletRequest;
	    HttpServletResponse response = (HttpServletResponse) servletResponse;
	    
	    Boolean isTokenFromCookie = Boolean.FALSE;
	    //先检查参数中是否带有token参数
	    String token = request.getParameter("token");
	    //如果参数中没有携带，则检查本地cookie中是否有token
	    if(StringUtils.isEmpty(token)){
	    	 Cookie[] cookies = request.getCookies();
	         if (null != cookies) {
	             for (Cookie cookie : cookies) {
	                 if (Constant.COOKIE_NAME.equals(cookie.getName())) {
	                 	token = cookie.getValue();
	                 	isTokenFromCookie = Boolean.TRUE;
	                    break;
	                 }
	             }
	         }
	    }
	    //如果以上两者都没有携带token,则跳转到服务端登录页面
	    if(StringUtils.isEmpty(token)){
	    	HashMap<String,String> params = new HashMap<String,String>();
        	params.put("redirectUrl", request.getRequestURL().toString());
        	response.sendRedirect(URLUtils.appendParams(Config.SSO_SERVER_LOGIN, params));
	    }
	    //如果有携带token,则发送到服务端做校验，校验通过，则通过过滤链;不通过,则跳转到服务端登录页面
	    else{
	    	if(SSOTokenVerifyProxy.validTokenThroughSSOServer(token)){
	    		if(!isTokenFromCookie){
		    		//创建cookie
		         	 Cookie cookie = new Cookie(Constant.COOKIE_NAME,token);
		             cookie.setPath(request.getServerName());
		             response.addCookie(cookie);
		    	}
	       		chain.doFilter(request, response);
	       	 }else{
	       		HashMap<String,String> params = new HashMap<String,String>();
	       		params.put("redirectUrl", request.getRequestURL().toString());
	        	response.sendRedirect(URLUtils.appendParams(Config.SSO_SERVER_LOGIN, params));
	       	 }
	    }
	}

	public void destroy() {
	}

}
